/**
 * Created by huangxiaolu on 2014/5/19.
 */
var http = require('http');
var port = process.env.port || 8989;
var url = require('url');
http.createServer(function(req,res)
{
    console.log('request received:'+req.headers.host +req.url);
    var options;
    var path =url.parse(req.url).path;
    if(path.indexOf('restapi')!==-1)
    {
        //var index = url.indexOf('/restapi');
        //var restPath = //url.substr(index);
        console.log('route restapi:'+url);
        options = {
            host:'10.8.14.28',
            port:8080,
            path:path,
            method:req.method,
            headers:req.headers
        }
    }
    else
    {
        options = {
            host:req.headers.host,
            port:80,
            path:path,
            method:req.method,
            headers:req.headers
        };
    }
    var innerReq = http.request(options,function(innerRes)
    {
        console.log("response header:"+JSON.stringify(innerRes.headers));
        res.writeHead(200,innerRes.headers);
        innerRes.pipe(res);
        innerRes.resume();
        res.end();
    }).on('error',function(e){
        console.log('proxy failed due to:'+ e.message);
    });
    innerReq.end(req.body);
}).listen(port,function(){
    console.log("gateway proxy listening on port:"+port);
});